package com.affablebean.model.dal;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;

import com.affablebean.model.entity.GenericEntity;

public abstract class AbstractDAL<E extends GenericEntity> implements GenericDAL<E> {

	private static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:xe";
	private static final String DB_USER_NAME = "affablebean";
	private static final String DB_PASSWORD = "ab";

	private final String tableName;

	public AbstractDAL(String tableName) {
		this.tableName = tableName;
	}

	@Override
	public int getCount() throws SQLException {
		int count = 0;
		try (Connection connection = createNewConnection()) {
			try (Statement statement = connection.createStatement()) {
				try (ResultSet resultSet = statement.executeQuery("SELECT COUNT(*) FROM " + tableName)) {
					if (resultSet.next()) count = resultSet.getInt(1);
				}
			}
		}
		return count;
	}

	Connection createNewConnection() throws SQLException {
		return DriverManager.getConnection(DB_URL, DB_USER_NAME, DB_PASSWORD);
	}

	java.sql.Date convertToSqlDate(Date date) {
		return new java.sql.Date(date.getTime());
	}

	abstract E createEntity(ResultSet resultSet) throws SQLException;
}
